﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using Sami_SMS_CRM_Business;
using Settings;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;

namespace Sami_SMS_CRM_UI
{
    public partial class crm_collection : BasePage
    {
        CollectionRepository repository = new CollectionRepository();
        int CollectionId
        {
            get 
            {
                try
                {
                    return int.Parse(hdfId.Value);
                }
                catch
                {
                    return 0;
                }
            }
            set { hdfId.Value = value.ToString(); }
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (!AllowManageAdvertisment())
            {
                RedirectToPage(AccessDeniedURL);
            }
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        void paging_PagingChange(object sender, EventArgs e)
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            pagingbottom.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            BindDataTable();
            pagingtop.Visible = (sender as UserControl.ucPaging).TotalPage > 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.Visible = (sender as UserControl.ucPaging).TotalPage > 1;
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadCombo();
                PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
                pagingtop.CurrentPage = 1;
                pagingtop.PageSize = PageSize;
                pagingtop.PageDisplay = PageDisPlay;
                pagingbottom.CurrentPage = 1;
                pagingbottom.PageSize = PageSize;
                pagingbottom.PageDisplay = PageDisPlay;
                BindDataTable();
            }
        }

        private void BindDataTable()
        {
            int currentPage = pagingtop.CurrentPage;
            int pageSize = pagingtop.PageSize;
            int totalRecord = 0;

            rptTable.DataSource = repository.GetAll(currentPage, pageSize, ref totalRecord);
            rptTable.DataBind();

            pagingtop.TotalRecord = totalRecord;
            pagingtop.Visible = pagingtop.TotalPage > 1;
            pagingbottom.TotalRecord = totalRecord;
            pagingbottom.Visible = pagingtop.TotalPage > 1;
            ltrTotalRow.Text = totalRecord.ToString();
        }

        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            pagingtop.PageSize = pagingbottom.PageSize = int.Parse((sender as DropDownList).SelectedValue);
            BindDataTable();
        }

        protected void rptTable_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            try
            {
                if (IsAdmin())
                {
                    int id = Convert.ToInt32(e.CommandArgument);
                    CollectionId = id;
                    switch (e.CommandName)
                    {
                        case "Edited":
                            var entity = repository.GetById(id);
                            SetData(entity);
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "dialog();", true);
                            break;
                        case "Deleted":
                            repository.DeleleById(id);
                            BindDataTable();
                            break;
                        case "ViewDetail":
                            txtCollectionValue.Text = repository.GetQuery(repository.GetById(CollectionId))
                                .Replace("crm_subscriber_classification", "crm_service_subscriber")
                                .Replace("guid_key", "ss_guid");
                            ViewDetail();
                            break;
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert(\"You don't have permission!\");", true);
                }
            }
            catch (Exception ex)
            {
                new LogRepository().InsertLog(ex);
            }
        }

        private void SetData(Sami_SMS_CRM_Business.crm_collection entity)
        {
            if (entity != null)
            {
                hdfAction.Value = "Edit";
                hdfId.Value = entity.collection_id.ToString();
                txtCollectionName.Text = entity.collection_name;
                ddlCollectionType.SelectedValue = entity.collection_type;
                if (entity.collection_value != null)
                {
                    txtSelectClause.Text = Server.HtmlDecode(entity.collection_value.Element("select").Value);
                    txtFromClause.Text = Server.HtmlDecode(entity.collection_value.Element("from").Value);
                    txtWhereClause.Text = Server.HtmlDecode(entity.collection_value.Element("where").Value);
                }
                txtDescription.Text = entity.description ?? string.Empty;
                ddlStatus.SelectedValue = entity.enabled.ToString();
            }
            else
            {
                hdfAction.Value = "AddNew";
                hdfId.Value = "0";
                txtCollectionName.Text = string.Empty;
                ddlCollectionType.SelectedIndex = 0;
                txtSelectClause.Text = string.Empty;
                txtFromClause.Text = string.Empty;
                txtWhereClause.Text = string.Empty;
                txtDescription.Text = string.Empty;
                ddlStatus.SelectedIndex = 0;
            }
            if (ddlCollectionType.SelectedValue == CollectionType.sqlcommand )
                SetVisiblePanel(true);
            else
                SetVisiblePanel(false);
        }

        private void ViewDetail()
        {
            try
            {
                grvDetail.DataSource = repository.GetSubscriber(CollectionId);
                grvDetail.DataBind();
                if (grvDetail.DataSource != null)
                {
                    lbTotal.Text = "Total: " + ((DataTable)grvDetail.DataSource).Rows.Count;
                }
                else
                {
                    lbTotal.Text = "Total: 0";
                }
                RegisterStartUpScrip("dialog2();");
            }
            catch (Exception e)
            {
                new LogRepository().InsertLog(e);
            }
        }

        private void LoadCombo()
        {
            ddlService.DataSource = new ServiceRepository().GetAll();
            ddlService.DataTextField = "service_name";
            ddlService.DataValueField = "sevice_id";
            ddlService.DataBind();
            ddlService.Items.Insert(0, new ListItem("-----------", ""));
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                if (CheckFullInfo())
                {
                    //Set properties
                    Sami_SMS_CRM_Business.crm_collection entity = repository.GetById(int.Parse(hdfId.Value)) ?? new Sami_SMS_CRM_Business.crm_collection();
                    entity.collection_name = txtCollectionName.Text;
                    entity.collection_type = ddlCollectionType.SelectedValue;
                    if (ddlCollectionType.SelectedValue == CollectionType.sqlcommand)
                    {
                        entity.collection_value = System.Xml.Linq.XElement.Parse(
                                "<query>" +
                                "<select>" + Server.HtmlEncode(txtSelectClause.Text) + "</select>" +
                                "<from>" + Server.HtmlEncode(txtFromClause.Text) + "</from>" +
                                "<where>" + Server.HtmlEncode(txtWhereClause.Text) + "</where>" +
                                "</query>"
                            );
                    }
                    entity.description = txtDescription.Text;
                    entity.enabled = bool.Parse(ddlStatus.SelectedValue);
                    switch (hdfAction.Value)
                    {
                        case "Edit":
                            repository.Update(entity);
                            BindDataTable();
                            break;
                        case "AddNew":
                            int id = repository.AddNew(entity);
                            if (ddlCollectionType.SelectedValue == CollectionType.directly)
                            {
                                hdfId.Value = id.ToString();
                                pndirectly.Visible = true;
                                entity.collection_value = System.Xml.Linq.XElement.Parse(
                                     "<query>" +
                                         "<select>*</select>" +
                                         "<from>crm_subscriber_import</from>" +
                                         "<where>collection_id = " + CollectionId + "</where>" +
                                     "</query>"
                                 );
                                repository.Update(entity);
                                BindDataTable();
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "dialog();", true);
                            }
                            else
                            {
                                BindDataTable();
                            }
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                new LogRepository().InsertLog(ex);
            }
        }

        protected void btnAddNew_Click(object sender, ImageClickEventArgs e)
        {
            if (IsAdmin())
            {
                SetData(null);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "dialog();", true);
            }
        }

        private bool CheckFullInfo()
        {
            string errMsg = string.Empty;
            if (string.IsNullOrEmpty(txtCollectionName.Text.Trim()))
                errMsg = "Collection name not allow null";
            if (ddlCollectionType.SelectedValue == CollectionType.sqlcommand)
            {
                if (string.IsNullOrEmpty(txtSelectClause.Text.Trim()))
                    errMsg = "Selet clause not allow null";
                if (string.IsNullOrEmpty(txtFromClause.Text.Trim()))
                    errMsg = "From clause not allow null";
            }
            if (errMsg == string.Empty)
                return true;
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "error", "dialog(); alert(\"" + Server.HtmlDecode(errMsg) + "\"); dialog();", true);
                return false;
            }
        }

        protected void grvDetail_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvDetail.PageIndex = e.NewPageIndex;
            ViewDetail();
        }

        protected void grvTestCollection_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvTestCollection.PageIndex = e.NewPageIndex;
            ViewTestCollectionValue();
        }

        protected void btnTestValue_Click(object sender, EventArgs e)
        {
            ViewTestCollectionValue();
        }

        private void ViewTestCollectionValue()
        {
            try
            {
                grvTestCollection.DataSource = repository.GetDataByQuery(txtCollectionValue.Text);
                grvTestCollection.DataBind();
            }
            catch (Exception e)
            {
                txtError.Text = e.Message;
            }
        }

        protected void ddlCollectionType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCollectionType.SelectedValue == CollectionType.sqlcommand)
            {
                SetVisiblePanel(true);
            }
            else if (ddlCollectionType.SelectedValue == CollectionType.directly)
            {
                SetVisiblePanel(false);
            }
            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "dialog();", true);
        }

        private void SetVisiblePanel(bool visible)
        {
            pnsqlcommand.Visible = visible;
            pndirectly.Visible = !visible;
            if (hdfAction.Value == "AddNew")
                pndirectly.Visible = false;
        }

        protected void btnUpLoad_Click(object sender, EventArgs e)
        {
            string fileName = string.Empty;
            string filePath = string.Empty;
            try
            {
                if (!uplSourceFile.HasFile)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "dialog(); alert('Please choose a Execel file to import data');", true);
                    return;
                }
                string excelContentType = "application/vnd.ms-excel";
                string excel2010ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                if (uplSourceFile.PostedFile.ContentType != excel2010ContentType
                    && uplSourceFile.PostedFile.ContentType != excelContentType)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "dialog(); alert('Please choose a Execel file to import data');", true);
                    return;
                }
                if (uplSourceFile.PostedFile.ContentLength > (1024 * 1024 * 200))
                {
                    RegisterStartUpScrip("registerDialog(); dialog($('#dialog-form2'));; alert('File size must be less than 200MB');");
                }
                fileName = Guid.NewGuid() + uplSourceFile.FileName;
                filePath = Path.Combine(Server.MapPath("~/App_Data"), fileName);
                uplSourceFile.SaveAs(filePath);
                //Insert dữ liệu
                SubscriberImportRepository.BulkInsert(filePath, hdfId.Value, ddlService.SelectedValue);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "dialog(); alert(\"" +ex.Message.Replace("\"","'").Replace(Environment.NewLine,"") + "\");", true);
            }
            finally
            {
                DeleteFile(filePath);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "dialog();", true);
            }
        }

        private void DeleteFile(string filepath)
        {
            if (File.Exists(filepath))
            {
                File.Delete(filepath);
            }
        }
    }
}